/**
 * Copyright 2009-2011 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.myjung.interceptor;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import net.myjung.Myjung;
import net.myjung.model.BaseObject;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Steve M. Jung
 */
public class LoggingInterceptor implements MethodInterceptor {
	private static Log logger = LogFactory.getLog(LoggingInterceptor.class);

	private Boolean beforeLoggerEnabled;
	private Boolean afterLoggerEnabled;
	private Boolean throwsLoggerEnabled = true;

	public LoggingInterceptor() {
		super();
	}
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Method method = invocation.getMethod();
		String methodName = method.getName();
		Object[] args = invocation.getArguments();

		try {
			beforeLogging(methodName, args);

			Object res = invocation.proceed();

			afterLogging(methodName, res);

			return res;

		} catch (Throwable t) {
			throwsLogging(methodName, t);
			throw t;
		}

	}

	private void beforeLogging(String methodName, Object[] args) {
		if (!beforeLoggerEnabled)
			return;
		StringBuffer buf = new StringBuffer("\r\n\tmehtod: ").append(methodName);
		if (!Myjung.isEmpty(args)) {
			for (int i = 0; i < args.length; i++) {
				buf.append("\r\n\t\tparameter").append(i).append(": ");
				Object arg = args[i];
				appendItems(buf, arg, "\t\t\t");
			}
		}
		logger.info(buf);
	}
	private void afterLogging(String methodName, Object res) {
		if (!afterLoggerEnabled)
			return;
		StringBuffer buf = new StringBuffer("\r\n\tmehtod: ").append(methodName);
		buf.append("\r\n\t\treturns: ");
		appendItems(buf, res, "\t\t\t");
		logger.info(buf);
	}
	private void throwsLogging(String methodName, Throwable t) {
		if (!throwsLoggerEnabled)
			return;
		StringBuffer buf = new StringBuffer("\r\n\tmehtod: ").append(methodName);
		buf.append("\r\n\t\tthrows: ");
		logger.error(buf);
		logger.error(t, t);
	}

	private static final String RN = "\r\n";
	private static final String TAB = "\t";
	private static final String ITEM = "item";
	public static void appendItems(StringBuffer buf, Object item, String tab) {
		String tab2 = tab + TAB;
		if (item == null) {
			buf.append(item);
		} else if (item instanceof Object[]) {
			Object[] objs = (Object[]) item;
			int i = 0;
			for (Object obj : objs) {
				buf.append(RN).append(tab).append(ITEM).append(i).append(": ");
				appendItems(buf, obj, tab2);
			}
		} else if (item instanceof Collection<?>) {
			Collection<?> col = (Collection<?>) item;
			int i = 0;
			for (Object obj : col) {
				buf.append(RN).append(tab).append(ITEM).append(i++).append(": ");
				appendItems(buf, obj, tab2);
			}
		} else if (item instanceof Map<?, ?>) {
			String tab3 = tab2 + TAB;
			Map<?, ?> map = (Map<?, ?>) item;
			Set<?> keySet = map.keySet();
			int i = 0;
			for (Object key : keySet) {
				Object value = map.get(key);
				buf.append(RN).append(tab).append(ITEM).append(i++).append(":");
				buf.append(RN).append(tab2).append("key: ").append(key);
				buf.append(RN).append(tab2).append("value: ");
				appendItems(buf, value, tab3);
			}
		} else if (item instanceof BaseObject) {
			BaseObject obj = (BaseObject) item;
			buf.append(RN).append(obj.toString(null, tab, "1"));
		} else if (item instanceof Date) {
			buf.append(Myjung.toXsdDateTimeString((Date) item));
		} else {
			buf.append(item);
		}
	}

	public Boolean getBeforeLoggerEnabled() {
		return beforeLoggerEnabled;
	}
	public void setBeforeLoggerEnabled(Boolean beforeLoggerEnabled) {
		this.beforeLoggerEnabled = beforeLoggerEnabled;
	}
	public Boolean getAfterLoggerEnabled() {
		return afterLoggerEnabled;
	}
	public void setAfterLoggerEnabled(Boolean afterLoggerEnabled) {
		this.afterLoggerEnabled = afterLoggerEnabled;
	}
	public Boolean getThrowsLoggerEnabled() {
		return throwsLoggerEnabled;
	}
	public void setThrowsLoggerEnabled(Boolean throwsLoggerEnabled) {
		this.throwsLoggerEnabled = throwsLoggerEnabled;
	}
}
